package com.ronin.pkimg.service;

import com.baidu.aip.ocr.AipOcr;
import com.qiniu.util.Auth;
import com.ronin.pkimg.bean.Config;
import com.ronin.pkimg.bean.QiniuTokenResp;
import com.ronin.pkimg.helper.OcrHelper;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.HashMap;

/**
 * Created by donghailong on 2020/4/3.
 */
@Service
public class TaskService {

    private static final String OCR_BASIC = "0";
    private static final String OCR_GENERAL_POS = "1";

    @Autowired
    private Config config;

    private QiniuTokenResp tokenResp = new QiniuTokenResp();


    @Async
    public ListenableFuture<QiniuTokenResp> execGetToken() {
        Auth auth = Auth.create(config.getAccess(), config.getSecret());
        final String token = auth.uploadToken(config.getBucket());
        if (!StringUtils.isEmpty(token)) {
            tokenResp.uptoken = token;
            tokenResp.setMessage("success");
            tokenResp.setCode(200);
        } else {
            tokenResp.setMessage("fail");
            tokenResp.setCode(-1);
        }
        return new AsyncResult<>(tokenResp);
    }


    @Async
    public ListenableFuture<String> execOcrAsyncTask(String pathUrl, String type) {
//        System.out.println("pathUrl=" + pathUrl + "Thread:" + Thread.currentThread().getName());
        AipOcr client = OcrHelper.getInstance().getClient();
        JSONObject res;
        if (StringUtils.isEmpty(type)) {
            type = OCR_BASIC;
        }
        switch (type) {
            case OCR_GENERAL_POS:
                res = client.generalUrl(pathUrl, new HashMap<>());
                break;
            case OCR_BASIC:
            default:
                res = client.basicGeneralUrl(pathUrl, new HashMap<>());
                break;
        }
        return new AsyncResult<>(res.toString());
    }

}
